/*
 * EncodeUtils.java
 *
 * Created on June 2, 2007, 8:28 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package info.javatech.jmf.server.util;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;
import org.apache.commons.lang.Validate;

/**
 *
 * @author afedotov
 */
public class EncodeUtils {
    
    private static Logger logger = Logger.getLogger(EncodeUtils.class.getName());
    
    public static byte[] encodeToByteArray(Object obj) {
        Validate.notNull(obj,"obj parameter should not be null");
        
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            XMLEncoder enc = new XMLEncoder(outStream);
            enc.writeObject(obj);
            enc.close();
            outStream.close();
            return outStream.toByteArray();
        } catch (IOException ex) {
            logger.throwing(EncodeUtils.class.getName(),"encodeToByteArray",ex);
            
            return new byte[0];
        }
    }
    
    public static String encodeToString(Object obj) {
        Validate.notNull(obj,"obj parameter should not be null");
        
        return new String(encodeToByteArray(obj));
    }
    
    public static Object decode(byte[] content) {
        Validate.notNull(content,"content parameter should not be null");
        
        try {
            InputStream is = new ByteArrayInputStream(content);
            
            XMLDecoder dec = new XMLDecoder(is);
            Object obj = dec.readObject();
            is.close();
            
            return obj;
        } catch (IOException ex) {
            logger.throwing(EncodeUtils.class.getName(),"encodeToString",ex);
            
            return null;
        }
    }
    
    public static Object decode(String content){
        Validate.notNull(content,"content parameter should not be null");
        try {
            return decode(content.getBytes("utf8"));
        } catch (UnsupportedEncodingException ex) {
            logger.throwing(EncodeUtils.class.getName(),"decode",ex);
            
            return null;
        }
    }
}
